/**
 * 
 */
package tp8.tsh.swing;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;

/**
 * @author tpanagopoulos
 * 
 */
public class JTerminal extends JPanel implements KeyListener {

	private List<String> lines;
	
	private String keyTyped;

	private static int OFFSET_X = 5;
	
	private static int OFFSET_Y = 13;
	
	private int curX = 1;
	
	public int getCurX() {
		return curX * OFFSET_X;
	}

	private int curY = 1;
	
	public int getCurY() {
		return curY * OFFSET_Y;
	}

	public JTerminal() {
		this.setBackground(Color.BLACK);
		this.setForeground(Color.blue);
		this.addKeyListener(this);
		
		lines = new ArrayList<String>();
		lines.add("");
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D) g;
		if ((keyTyped != null) && (keyTyped.length() > 0)) {
			
			this.clearCursor();
			
			if (keyTyped.equals("\n")) {
				this.enter();
			} else if (keyTyped.equals("")) {
				this.backSpace();
			} else {
				int pos = curY - 1;
				String line = lines.get(pos) + keyTyped;
				lines.set(pos, line);
				keyTyped = null;
				curX++;
			}
			this.drawCursor();
			
			paintTerminal(g2d);
		}

	}
	
	private void clearCursor() {
		
		StringBuilder line = new StringBuilder(lines.get(curY - 1));
		line.delete(curX - 1, curX);
		lines.set(curY - 1, line.toString());
		
	}
	
	private void drawCursor() {
		
		StringBuilder line = new StringBuilder(lines.get(curY - 1));
		line.insert(curX - 1, "|");
		lines.set(curY - 1, line.toString());
		
	}
	
	private void enter() {
		curY++;
		curX = 1;
		lines.add("");
	}
	
	private void backSpace() {
		if (curX > 1) {
//			curX--;
		} else if (curY > 1) {
			curY--;
			curX = lines.get(curY - 1).length() + 1;
		}
		StringBuilder line = new StringBuilder(lines.get(curY - 1));
		if (curX > 1) {
			--curX;
			int x = curX - 1;
			line.deleteCharAt((x));
		}
		lines.set(curY - 1, line.toString());
	}
	
	private void paintTerminal(Graphics2D g2d) {
		String line;
		for (int i = 0; i < lines.size(); i++) {
			line = lines.get(i);
			g2d.drawString(line, OFFSET_X, (i + 1) * OFFSET_Y);
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {
		int keyCode = e.getKeyCode();
		char keyChar = e.getKeyChar();
		if (keyChar > 0) {
			keyTyped = "" + keyChar;
			this.repaint();
		} else if (keyCode > 0) {
			keyTyped = e.getKeyText(keyCode);
			this.repaint();
		}
	}

	@Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub

	}

}
